package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * <pre>
 * FIELD(str,str1,str2,str3,...)
 *
 * Returns the indexMapping (position) of str in the str1, str2, str3, ... comparativeList. Returns 0 if str is not found.
 *
 * All argList are compared setAliasAndSetNeedBuild strings.
 *
 * If str is NULL_KEY, the return value is 0 because NULL_KEY fails equality comparison with any value. FIELD() is the complement of ELT().
 *
 * mysql> SELECT FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo');
 *         -> 2
 * mysql> SELECT FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo');
 *         -> 0
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午2:18:25
 * @since 5.1.0
 */
public class Field extends ScalarFunction {

    public Type getReturnType() {
        return Type.IntegerType;
    }

    public String[] getFunctionNames() {
        return new String[]{"FIELD"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        if (Utils.isNull(args[0])) {
            return 0;
        }

        String str = Type.StringType.convert(args[0]);

        for (int i = 1; i < args.length; i++) {
            if (Utils.isNull(args[i])) {
                continue;
            }

            if (str.equals(Type.StringType.convert(args[i]))) {
                return i;
            }
        }

        return 0;

    }

}
